package cz.data.domain.metadata.controller;

import cz.data.common.base.BaseController;
import cz.data.common.base.BaseResponse;
import cz.data.common.base.SimpleDataResponse;
import cz.data.common.core.DataSelectOption;
import cz.data.common.core.JsonPage;
import cz.data.common.support.db.driver.JdbcCustomOperation;
import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;
import cz.data.common.support.db.core.PageResult;
import cz.data.common.validate.ValidationGroups;
import cz.data.domain.driver.rpc.JdbcDriverFeign;
import org.apache.commons.lang3.StringUtils;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cz.data.domain.metadata.mapstruct.MetadataSourceMapper;
import cz.data.domain.metadata.model.dto.MetadataSourceDto;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.model.query.DbDataQuery;
import cz.data.domain.metadata.model.query.MetadataSourceQuery;
import cz.data.domain.metadata.model.vo.MetadataSourceVo;
import cz.data.domain.metadata.service.MetadataSourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = {"数据源API"})
@RestController
@RequestMapping("/sources")
public class MetadataSourceController extends BaseController {

    @Autowired
    private MetadataSourceService metadataSourceService;

    @Autowired
    private MetadataSourceMapper metadataSourceMapper;

    @Resource
    JdbcDriverFeign jdbcDriverFeign;

    @ApiOperation(value = "数据源-获取详情", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @GetMapping("/{id}")
    public SimpleDataResponse<MetadataSourceVo> getMetadataSourceById(@PathVariable String id) {
        MetadataSourceEntity metadataSourceEntity = metadataSourceService.getMetadataSourceById(id);
        return new SimpleDataResponse<>(metadataSourceMapper.toVO(metadataSourceEntity));
    }

    @ApiOperation(value = "数据源-获取列表", notes = "查询数据源列表")
    @GetMapping("/list")
    public SimpleDataResponse<List<MetadataSourceVo>> getMetadataSourceList() {
        List<MetadataSourceEntity> list = metadataSourceService.getMetadataSourceList();
        List<MetadataSourceVo> collect = list.stream().map(metadataSourceMapper::toVO).collect(Collectors.toList());
        return new SimpleDataResponse<>(collect);
    }

    @ApiOperation(value = "数据源-获取列表", notes = "查询数据源列表")
    @GetMapping("/selectOptions")
    public SimpleDataResponse<List<DataSelectOption>> getMetadataSourceSelectOptions(
            @RequestParam(value = "capability", required = false) List<String> capability,
            @RequestParam(value = "type", required = false) String dbType) {
        List<MetadataSourceEntity> list = metadataSourceService.getMetadataSourceSelectOptions(capability, dbType);
        List<DataSelectOption> collect = list.stream()
                .map(ele -> new DataSelectOption(ele.getId(), ele.getSourceName(), ele.getId()))
                .collect(Collectors.toList());
        return new SimpleDataResponse<>(collect);
    }

    @ApiOperation(value = "数据源-分页查询", notes = "分页查询信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "metadataSourceQuery", value = "查询实体metadataSourceQuery", required = true, dataTypeClass = MetadataSourceQuery.class)
    })
    @GetMapping("/page")
    public SimpleDataResponse<JsonPage<MetadataSourceVo>> getMetadataSourcePage(MetadataSourceQuery metadataSourceQuery) {
        QueryWrapper<MetadataSourceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(metadataSourceQuery.getSourceName()), "s.source_name", metadataSourceQuery.getSourceName());
        IPage<MetadataSourceEntity> page = metadataSourceService.pageWithAuth(new Page<>(metadataSourceQuery.getPageNum(), metadataSourceQuery.getPageSize()), queryWrapper);
        List<MetadataSourceVo> collect = page.getRecords().stream().map(metadataSourceMapper::toVO).collect(Collectors.toList());
        JsonPage<MetadataSourceVo> jsonPage = new JsonPage<>(page.getCurrent(), page.getSize(), page.getTotal(), collect);
        return new SimpleDataResponse<>(jsonPage);
    }

    @ApiOperation(value = "数据源-添加", notes = "根据metadataSourceDto对象添加信息")
    @ApiImplicitParam(name = "metadataSourceDto", value = "详细实体metadataSourceDto", required = true, dataType = "MetadataSourceDto")
    @PostMapping()
    public BaseResponse saveMetadataSource(@RequestBody @Validated({ValidationGroups.Insert.class}) MetadataSourceDto metadataSourceDto) {
        metadataSourceService.saveMetadataSource(metadataSourceDto);
        return BaseResponse.success();
    }

    @ApiOperation(value = "数据源-修改", notes = "根据url的id来指定修改对象，并根据传过来的信息来修改详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "metadataSourceDto", value = "详细实体metadataSourceDto", required = true, dataType = "MetadataSourceDto")
    })
    @PutMapping("/{id}")
    public BaseResponse updateMetadataSource(@PathVariable String id, @RequestBody @Validated({ValidationGroups.Update.class}) MetadataSourceDto metadataSourceDto) {
        metadataSourceService.updateMetadataSource(metadataSourceDto);
        return BaseResponse.success();
    }

    @ApiOperation(value = "数据源-删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @DeleteMapping("/{id}")
    public BaseResponse deleteMetadataSourceById(@PathVariable String id) {
        metadataSourceService.deleteMetadataSourceById(id);
        return BaseResponse.success();
    }

    @ApiOperation(value = "数据源-批量删除", notes = "根据url的ids来批量删除对象")
    @ApiImplicitParam(name = "ids", value = "ID集合", required = true, dataType = "List", paramType = "path")
    @DeleteMapping("/batch/{ids}")
    public BaseResponse deleteMetadataSourceBatch(@PathVariable List<String> ids) {
        metadataSourceService.deleteMetadataSourceBatch(ids);
        return BaseResponse.success();
    }

    @ApiOperation(value = "数据源-测试连通性", notes = "根据数据库配置信息检测数据库连通性")
    @ApiImplicitParam(name = "dataSource", value = "详细实体dataSource", required = true, dataType = "DataSourceDto")
    @PostMapping("/checkConnection")
    public BaseResponse checkConnection(@RequestBody @Validated({ValidationGroups.Insert.class}) MetadataSourceDto metadataSourceDto) {
        return metadataSourceService.checkConnection(metadataSourceDto);
    }

    @ApiOperation(value = "数据库表", notes = "根据数据源的id来获取指定数据库表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    })
    @GetMapping("/{id}/tables")
    public SimpleDataResponse<List<DbTable>> getDbTables(@PathVariable String id) {
        List<DbTable> tables = metadataSourceService.getDbTables(id);
        return new SimpleDataResponse<>(tables);
    }

    @ApiOperation(value = "数据库表结构", notes = "根据数据源的id来获取指定数据库表的表结构")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "tableName", value = "数据库表", required = true, dataType = "String", paramType = "path")
    })
    @GetMapping("/{id}/{tableName}/columns")
    public SimpleDataResponse<List<DbColumn>> getDbTableColumns(@PathVariable String id, @PathVariable String tableName) {
        List<DbColumn> columns = metadataSourceService.getDbTableColumns(id, tableName);
        return new SimpleDataResponse<>(columns);
    }

    @ApiOperation(value = "获取SQL结果", notes = "根据数据源的id来获取SQL结果")
    @ApiImplicitParam(name = "dbDataQuery", value = "详细实体dbDataQuery", required = true, dataType = "DbDataQuery")
    @PostMapping("/queryList")
    public SimpleDataResponse<List<Map<String, Object>>> queryList(@RequestBody @Validated DbDataQuery dbDataQuery) {
        JdbcCustomOperation operation = new JdbcCustomOperation();
        operation.setSource(dbDataQuery.getDataSourceId());
        operation.setCommand(dbDataQuery.getSql());
        operation.setPageSize(1000);
        PageResult<Map<String, Object>> pageResult = jdbcDriverFeign.instruct(operation);
        return new SimpleDataResponse<>(pageResult.getData());
    }

    @ApiOperation(value = "分页获取SQL结果", notes = "根据数据源的id来分页获取SQL结果")
    @ApiImplicitParam(name = "dbDataQuery", value = "详细实体dbDataQuery", required = true, dataType = "DbDataQuery")
    @PostMapping("/queryByPage")
    public SimpleDataResponse<PageResult<Map<String, Object>>> queryByPage(@RequestBody @Validated DbDataQuery dbDataQuery) {
        JdbcCustomOperation operation = new JdbcCustomOperation();
        operation.setSource(dbDataQuery.getDataSourceId());
        operation.setCommand(dbDataQuery.getSql());
        operation.setPageNum(dbDataQuery.getPageNum());
        operation.setPageSize(dbDataQuery.getPageSize());
        PageResult<Map<String, Object>> pageResult = jdbcDriverFeign.instruct(operation);
        pageResult.setPageNum(dbDataQuery.getPageNum()).setPageSize(dbDataQuery.getPageSize());
        return new SimpleDataResponse<>(pageResult);
    }

    @ApiOperation(value = "同步数据源元数据", notes = "根据url的id来指定同步数据源元数据")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @PostMapping("/sync/{id}")
    public BaseResponse syncMetadata(@PathVariable String id) {
        metadataSourceService.syncMetadata(id);
        return BaseResponse.success();
    }

    @ApiOperation(value = "数据库设计文档", notes = "根据url的id来指定生成数据库设计文档对象")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @PostMapping("/word/{id}")
    public void wordMetadata(@PathVariable String id, HttpServletResponse response) throws Exception {
        // 清空response
        response.reset();
        // 设置response的Header
        response.setContentType("application/octet-stream;charset=utf-8");
        // 设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.addHeader("Content-Disposition", "attachment;filename=" + new String("数据库设计文档.doc".getBytes()));
        Document doc = metadataSourceService.wordMetadata(id);
        OutputStream out = response.getOutputStream();
        doc.save(out, SaveOptions.createSaveOptions(SaveFormat.DOC));
        out.flush();
        out.close();
    }

    @ApiOperation(value = "刷新参数缓存", notes = "刷新参数缓存")
    @GetMapping("/refresh")
    public BaseResponse refreshMetadata() {
        metadataSourceService.refreshMetadata();
        return BaseResponse.success();
    }
}
